<template>
  <div class="userlevel-page page-main">
    <search-form :model="searchParams" @search="search">
      <a-form-item label="名称" name="prop">
        <a-input v-model:value="searchParams.prop" placeholder="请输入" />
      </a-form-item>
    </search-form>
    <div class="table-toolbar">
      <add-button @click="add()" />
    </div>
    <g-table
      ref="tableRef"
      :columns="columns"
      :api="userlevelList"
      :params="searchParams"
    />

    <userlevelDetail
      v-model:visible="visible"
      :data="activeRow"
      @change="search(false)"
    />
  </div>
</template>

<script setup lang="tsx">
import { userlevelDel, userlevelList, levelUseApi } from "../api";
import type { Iuserlevel, userlevel } from "./entity";
import userlevelDetail from "./detail.vue";
import { Modal } from "ant-design-vue";

const searchParams = reactive({
  prop: "",
});

let visible = $ref(false);

const { tableRef, columns, search } = useTable<Iuserlevel>([
  { title: "标题", dataIndex: "prop" },
  { title: "ID", dataIndex: "id" },
  {
    title: "等级图标",
    dataIndex: "icon",

    customRender: ({ record }) =>
      record.icon ? <img class="img-thumbnail" src={record.icon} /> : "",
  },
  { title: "等级名称", dataIndex: "name" },
  { title: "经验", dataIndex: "experience" },
  { title: "享受折扣(%)", dataIndex: "discount" },
  {
    title: "状态",
    dataIndex: "status",
    width: 120,
    customRender: ({ record }) => (
      <>
        <a-switch
          onClick={() => onchangeIsShow(record)}
          v-model:checked={record.isShow}
          inline-prompt
          checkedChildren="开启"
          unCheckedChildren="关闭"
        />
      </>
    ),
  },
  {
    title: "操作",
    dataIndex: "op",
    customRender: ({ record }) => (
      <>
        <table-button onClick={() => add(record)}>编辑</table-button>
        <confirm-button danger onClick={() => remove(record)}>
          删除
        </confirm-button>
      </>
    ),
  },
]);

let activeRow = $ref<Partial<Iuserlevel>>({});
function add(row: Partial<Iuserlevel> = {}) {
  activeRow = { ...row };
  visible = true;
}

function remove({ id }: Iuserlevel) {
  userlevelDel(id as number).then(() => {
    AntMessage.success("已删除");
    search(false);
  });
}
function onchangeIsShow(row: Iuserlevel) {
  if (row.isShow == false) {
    setState(row);
  } else {
    Modal.confirm({
      title: "提示",
      content: "该操作会导致对应用户等级隐藏，请谨慎操作",
      onOk() {
        setState(row);
      },
    });
  }
}
async function setState(row: Iuserlevel) {
  await levelUseApi({ id: row.id, isShow: !row.isShow }).catch(() => {
    row.isShow = !row.isShow;
  });
  AntMessage.success("修改成功");
  search(false);
}
</script>

<style lang="scss"></style>
